package com.kaiwukj.android.ufamily.mvp.ui.page.home.home;

import android.os.Bundle;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpFragment;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.di.component.DaggerHomeV20Component;
import com.kaiwukj.android.ufamily.di.module.HomeV20Module;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.ActiveEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.GlobalEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.HomeEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.params.CommentParams;
import com.kaiwukj.android.ufamily.mvp.http.entity.params.DynamicListParams;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.CommentResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.DynamicResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.FriendRecoResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.report.ReportCardFragment;
import com.kaiwukj.android.ufamily.mvp.ui.page.home.home.contract.HomeV20Contract;
import com.kaiwukj.android.ufamily.mvp.ui.page.home.home.presenter.HomeV20Presenter;
import com.kaiwukj.android.ufamily.mvp.ui.widget.SpaceItemDecoration;
import com.kaiwukj.android.ufamily.utils.DialogUtilsKt;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;

import static com.kaiwukj.android.ufamily.mvp.ui.page.home.home.presenter.HomeV20PresenterKt.ATTENTION;
import static com.kaiwukj.android.ufamily.mvp.ui.page.home.home.presenter.HomeV20PresenterKt.BLOCK_DYNAMIC;
import static com.kaiwukj.android.ufamily.mvp.ui.page.home.home.presenter.HomeV20PresenterKt.BLOCK_USER;
import static com.kaiwukj.android.ufamily.mvp.ui.page.home.home.presenter.HomeV20PresenterKt.DYNAMIC_DELETE;
import static com.kaiwukj.android.ufamily.mvp.ui.page.home.home.presenter.HomeV20PresenterKt.DYNAMIC_LIKE;
import static com.kaiwukj.android.ufamily.mvp.ui.page.home.home.presenter.HomeV20PresenterKt.DYNAMIC_LIKE_CANCEL;

public class HomeV20Fragment extends BaseMvpFragment<HomeV20Presenter> implements HomeV20Contract.View {

    @BindView(R.id.smart_refresh_home)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.rv_home)
    RecyclerView mRvHome;
    @BindView(R.id.qmui_empty_view)
    QMUIEmptyView emptyView;

    private BottomSheetDialog commentDialog;//评论dialog(底部弹出)
    private EditText etCommentInput;

    private HomeAdapter mHomeAdapter;
    private MaterialDialog mDynamicEventDialog;

    private int pIndex;//

    private int page = 1;
    private int pageSize = 10;

    private boolean isLoadingMore = false;

    private boolean isNeedRefresh = false;
    private boolean isRemoveNotice = false;//是否手动移除notice

    private int eventPos = -1;
    private int commentDynamicId;

    public static HomeV20Fragment newInstance(int index) {
        Bundle args = new Bundle();
        args.putInt("parent", index);
        HomeV20Fragment fragment = new HomeV20Fragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        super.setupFragmentComponent(appComponent);
        DaggerHomeV20Component
                .builder()
                .appComponent(appComponent)
                .homeV20Module(new HomeV20Module(this))
                .build().inject(this);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            pIndex = bundle.getInt("parent");
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_20;
    }


    @Override
    protected void initView() {

        mRvHome.setLayoutManager(new LinearLayoutManager(getContext()));
        mRvHome.addItemDecoration(new SpaceItemDecoration(10));
        mHomeAdapter = new HomeAdapter();

        mHomeAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.iv_close) {
                mHomeAdapter.removeAt(position);
                isRemoveNotice = true;
            }
        });

        mHomeAdapter.setOnDynamicEvent(new HomeAdapter.DynamicEvent() {

            @Override
            public void onRefreshFriend() {
                mPresenter.refreshFriendReco(pIndex);
            }

            @Override
            public void onActiveMore() {
                ARouter.getInstance().build(ARouterUrlKt.ActivePageUrl)
                        .withInt("type", pIndex == 1 ? 1 : 2).navigation();
            }

            @Override
            public void onPostLike(int id, int position) {
                eventPos = position;
                mPresenter.postLike(id);
            }

            @Override
            public void onPostCancelLike(int id, int position) {
                eventPos = position;
                mPresenter.postLikeCancel(id);
            }

            @Override
            public void onAttention(int id, int position) {
                eventPos = position;
                mPresenter.postAttention(id);
            }

            @Override
            public void onAttentionById(int userId) {
                eventPos = -1;
                mPresenter.postAttention(userId);
            }

            @Override
            public void onComment(int commentId, int childPos) {
                eventPos = childPos;
                showCommentInput(commentId);
            }

            @Override
            public void onMoreEvent(int eventId, int eventPosition, Object ext) {
                eventPos = eventPosition;
                int userId = (int) ext;
                mDynamicEventDialog = DialogUtilsKt.showBottomReportDialog(getContext(), v -> {
                    switch (v.getId()) {
                        //屏蔽帖子
                        case R.id.tv_block_this_content:
                            mPresenter.postBlockUserOrDynamic(eventId, false);
                            mDynamicEventDialog.cancel();
                            break;
                        //屏蔽用户
                        case R.id.tv_block_this_user:
                            // BlockCardOrUserRequest requestUser = new BlockCardOrUserRequest(cardUserId, 2);
                            //assert mPresenter != null;
                            // mPresenter.requestBlockUserOrCard(requestUser);
                            mPresenter.postBlockUserOrDynamic(userId, true);
                            mDynamicEventDialog.dismiss();
                            break;
                        //举报
                        case R.id.tv_report_this_user:
                            mDynamicEventDialog.dismiss();
                            //start(ReportCardFragment.newInstance(dynamicId));
                            ARouter.getInstance().build(ARouterUrlKt.SocialCircleUrl)
                                    .withString("FRAGMENT_KEY", ReportCardFragment.REPORT_PAGE)
                                    .withSerializable("dynamicResult", mHomeAdapter.getDynamicByPosition(eventPosition))
                                    .navigation();
                            break;
                        case R.id.tv_delete:
                            //    mPresenter.delSocialCard(mCardId);
                            mPresenter.postDelDynamic(eventId);
                            mDynamicEventDialog.dismiss();
                            break;
                    }
                }, userId == getApp().getUserInfo().getId());
            }

            @Override
            public void onDynamicContract(int position) {
                mRvHome.smoothScrollToPosition(position);
                LogUtils.d("pos-------------------------_>" + position);
            }
        });
       /* View emptyView = View.inflate(mContext, R.layout.empty_view_common_container, null);
        mHomeAdapter.setEmptyView(emptyView);*/
        mRvHome.setAdapter(mHomeAdapter);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                // mPresenter.fetchDynamic(++page);
                isLoadingMore = true;
                ++page;
                //  if (pIndex == 0) {
                mPresenter.fetchHomeMoreDynamic(getDynamicParams(false), pIndex);
               /* } else {
                    mPresenter.fetchHome02Dynamic(getDynamicParams(false));
                }*/
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initData();
            }
        });

    }

    @Override
    protected void initData(Bundle s) {
    }

    @Override
    protected void initDataSupport() {
        super.initDataSupport();
        //mPresenter.fetchDynamic(page = 1);
        emptyView.show(true);
        initData();
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (isNeedRefresh) {
            isNeedRefresh = false;
            emptyView.show(true);
            initData();
        }
    }

    private DynamicListParams getDynamicParams(boolean isRefresh) {
        DynamicListParams params = new DynamicListParams();
        if (!isRefresh && mHomeAdapter != null) {
            params.setStartId((int) mHomeAdapter.getLastDynamicId());
        } else {
            params.setStartId(0);
        }
        params.setPageSize(pageSize);
        return params;
    }

    private void initData() {
        page = 1;
        mPresenter.initHomeData(getDynamicParams(true), pIndex);
      /*  if (pIndex == 0) {
            mPresenter.initHomeData(getDynamicParams(true), pIndex);
        } else {
            mPresenter.initHome02Data(getDynamicParams(true), pIndex);
        }*/
    }

    private void showCommentInput(int dynamicId) {
        commentDynamicId = dynamicId;
        if (commentDialog == null) {
            commentDialog = new BottomSheetDialog(Objects.requireNonNull(getContext()), R.style.BottomSheetEdit);
            commentDialog.setContentView(R.layout.dialog_comment_bottom_sheet);
            etCommentInput = commentDialog.findViewById(R.id.et_social_circle_reply_comment);
            Button btnComment = commentDialog.findViewById(R.id.btn_comment_send);
            assert etCommentInput != null;
            etCommentInput.setOnEditorActionListener((v, actionId, event) -> {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    String content = etCommentInput.getText().toString().trim();
                    if (StringUtils.isEmpty(content)) {
                        showMessage("内容不能为空");
                        return true;
                    }
                    commentDynamic(commentDynamicId, content);
                    commentDialog.cancel();
                }
                return false;
            });

            if (btnComment != null) {
                btnComment.setOnClickListener(v -> {
                    String content = etCommentInput.getText().toString().trim();
                    if (StringUtils.isEmpty(content)) {
                        showMessage("内容不能为空");
                        return;
                    }
                    commentDynamic(commentDynamicId, content);
                    commentDialog.cancel();
                });
            }
            commentDialog.setOnCancelListener(dialog -> {
                KeyboardUtils.hideSoftInput(refreshLayout);
            });
        }
        etCommentInput.setFocusable(true);
        etCommentInput.setFocusableInTouchMode(true);
        etCommentInput.requestFocus();
        commentDialog.show();
        KeyboardUtils.showSoftInput(refreshLayout);
    }

    private void commentDynamic(int dynamicId, String commentContent) {
        CommentParams params = new CommentParams();
        params.setDynamicId(dynamicId);
        params.setCommentContent(commentContent);
        mPresenter.postComment(params);
    }

    @Override
    public void onTaskErr(int taskId) {
        super.onTaskErr(taskId);
        emptyView.hide();
        finishFetch();
        eventPos = -1;
    }

    @Override
    public void onTaskSuccess(int taskId) {
        super.onTaskSuccess(taskId);
        if (taskId == DYNAMIC_LIKE) {
            mHomeAdapter.postLike(true, eventPos);
            eventPos = -1;
        } else if (taskId == DYNAMIC_LIKE_CANCEL) {
            mHomeAdapter.postLike(false, eventPos);
            eventPos = -1;
        } else if (taskId == ATTENTION) {
            showMessage("关注成功");
            if (pIndex == 0) {
                mHomeAdapter.getRecoFriendAdapter().removeAt(eventPos);
                if (mHomeAdapter.getRecoFriendAdapter().getItemCount() <= 0) {
                    mPresenter.refreshFriendReco(0);
                }
            } else if (pIndex == 1) {
                mHomeAdapter.getFriendAdapter().removeAt(eventPos);
                if (mHomeAdapter.getFriendAdapter().getItemCount() <= 0) {
                    mHomeAdapter.removeItemByFlag(HomeMultiItemEntity.HOME_FRIEND_RECOMMEND);
                }
            } else {
                mHomeAdapter.getFriendAdapter().removeAt(eventPos);
                if (mHomeAdapter.getFriendAdapter().getItemCount() <= 0) {
                    mHomeAdapter.removeItemByFlag(HomeMultiItemEntity.HOME_FRIEND_RECOMMEND);
                }
            }
            eventPos = -1;
        } else if (taskId == BLOCK_USER) {
            initData();
            eventPos = -1;
        } else if (taskId == BLOCK_DYNAMIC) {
            mHomeAdapter.delDynamic(eventPos);
            eventPos = -1;
        } else if (taskId == DYNAMIC_DELETE) {
            mHomeAdapter.delDynamic(eventPos);
            eventPos = -1;
        }
    }

    private void finishFetch() {
        if (isLoadingMore) {
            isLoadingMore = false;
            refreshLayout.finishLoadMoreWithNoMoreData();
        } else {
            refreshLayout.finishRefresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHomeEvent(HomeEvent event) {
        int eventId = event.getDynamicId();
        int eventPos = -1;
        if (mHomeAdapter != null) {
            eventPos = mHomeAdapter.getDynamicPositionById(eventId);
        }
        switch (event.getEvent()) {
            case HomeEvent.DYNAMIC_PUBLISH:
            case HomeEvent.USER_BLOCK:
            case HomeEvent.UPDATE_DATA:
                isNeedRefresh = true;
                break;
            case HomeEvent.DYNAMIC_BLOCK:
            case HomeEvent.DYNAMIC_DELETE:
                if (eventPos > -1 && mHomeAdapter != null) {
                    mHomeAdapter.removeAt(eventPos);
                }
                break;
            case HomeEvent.POST_LIKE:
                if (eventPos > -1) {
                    mHomeAdapter.postLike(true, eventPos);
                }
                break;
            case HomeEvent.POST_LIKE_CANCEL:
                if (eventPos > -1) {
                    mHomeAdapter.postLike(false, eventPos);
                }
                break;
            case HomeEvent.POST_COMMENT:
                this.eventPos = eventPos;
                Map<String, Object> commentMap = (Map<String, Object>) event.getObj();
                int commentId = (int) commentMap.get("commentId");
                CommentParams commentParams = (CommentParams) commentMap.get("commentParams");
                onCommentResult(commentId, commentParams);
                break;
            case HomeEvent.DELETE_COMMENT:
                int pos = mHomeAdapter.getDynamicPositionById(eventId);
                mHomeAdapter.delComment(pos);
                break;
            case HomeEvent.UPDATE_POSITION:
                DynamicResult dynamicResult = (DynamicResult) event.getObj();
                if (dynamicResult != null) {
                    HomeMultiItemEntity entity = new HomeMultiItemEntity(HomeMultiItemEntity.HOME_DYNAMIC);
                    entity.setDynamicResult(dynamicResult);
                    mHomeAdapter.setData(eventPos, entity);
                }
                break;
            case HomeEvent.POST_ATTENTION:
                LogUtils.d("event------------------->" + GsonUtils.toJson(event));
                mHomeAdapter.postAttentionByUserId((Integer) event.getObj(), true);
                break;
            case HomeEvent.POST_ATTENTION_CANCEL:
                mHomeAdapter.postAttention(mHomeAdapter.getDynamicPositionById(eventId), false);
                break;
        }
    }

    @Subscribe
    public void onGlobalEvent(GlobalEvent event) {
        if (event.getCode() == GlobalEvent.REFRESH) {
            isNeedRefresh = true;
        }
    }

    @Subscribe
    public void onActiveEvent(ActiveEvent event) {
        if (event.getCode() == ActiveEvent.JOIN) {
            mHomeAdapter.postJoin((Integer) event.getExt(), true);
        } else {
            mHomeAdapter.postJoin((Integer) event.getExt(), false);
        }
    }

    @Override
    public void onFetchDynamic(@NotNull List<DynamicResult> list) {
        mHomeAdapter.addDynamic(list, true);
        if (list.size() < pageSize) {
            refreshLayout.finishLoadMoreWithNoMoreData();
        } else {
            refreshLayout.finishLoadMore(true);
        }
    }

    @Override
    public void onFetchData(@NotNull HomeData01Zip result) {
        refreshLayout.finishRefresh();
        emptyView.hide();

        if (pIndex == 1 || pIndex == 2) {
            showHomeData(result);
        } else {
            showNormalData(result);
        }

        if (mHomeAdapter.getItemCount() == 0) {
            emptyView.show("暂没有内容", "");
        }
    }

    @Override
    public void onFetchFriend(@NotNull List<FriendRecoResult> results) {

        if (results.size() > 0) {
            mHomeAdapter.getRecoFriendAdapter().setNewInstance(results);
        } else {
            mHomeAdapter.removeItemByFlag(HomeMultiItemEntity.HOME_FRIEND_RECOMMEND_BETA);
        }
    }

    @Override
    public void onCommentResult(int commentId, @NotNull CommentParams params) {
        if (etCommentInput != null) {
            etCommentInput.setText("");
        }
        CommentResult commentResult = new CommentResult();
        commentResult.setId(commentId);
        commentResult.setDynamicId(params.getDynamicId());
        commentResult.setCommentContent(params.getCommentContent());
        commentResult.setNickname(getApp().getUserInfo().getNickName());
        commentResult.setFromUid(getApp().getUserInfo().getId());
        if (mHomeAdapter != null) {
            mHomeAdapter.postComment(eventPos, commentResult);
        }
        eventPos = -1;
    }

    //交错数据
    private void showHomeData(HomeData01Zip result) {
        List<HomeMultiItemEntity> mData = new ArrayList<>();
        if (result.getCommunityInfoResult() != null && result.getCommunityInfoResult().getId() > 0) {
            HomeMultiItemEntity bannerEntity = new HomeMultiItemEntity(HomeMultiItemEntity.HOME_BANNER);
            bannerEntity.setCommunityInfo(result.getCommunityInfoResult());
            mData.add(bannerEntity);
        }

        List<HomeMultiItemEntity> tempData = new ArrayList<>();
        if (result.getFriendRecoResults() != null && result.getFriendRecoResults().size() > 0) {
            HomeMultiItemEntity friendRecoEntity = new HomeMultiItemEntity(HomeMultiItemEntity.HOME_FRIEND_RECOMMEND);
            friendRecoEntity.setFriendList(result.getFriendRecoResults());
            tempData.add(friendRecoEntity);
        }

        if (result.getActiveResults() != null && result.getActiveResults().size() > 0) {
            HomeMultiItemEntity activeEntity = new HomeMultiItemEntity(HomeMultiItemEntity.HOME_ACTIVE);
            activeEntity.setActives(result.getActiveResults());
            tempData.add(activeEntity);
        }

        if (result.getCommunityNewsResult() != null && result.getCommunityNewsResult().size() > 0) {
            HomeMultiItemEntity newsEntity = new HomeMultiItemEntity(HomeMultiItemEntity.HOME_COMMUNITY_NEWS);
            newsEntity.setCommunityNews(result.getCommunityNewsResult());
            tempData.add(newsEntity);
        }

        if (result.getDynamicResults() != null) {
            int flag = 0;
            for (DynamicResult dynamicResult : result.getDynamicResults()) {
                if (flag == 2 && tempData.size() > 0) {
                    mData.add(tempData.get(0));
                    tempData.remove(0);
                    flag = 0;
                } else {
                    HomeMultiItemEntity dynamicEntity = new HomeMultiItemEntity(HomeMultiItemEntity.HOME_DYNAMIC);
                    dynamicEntity.setDynamicResult(dynamicResult);
                    mData.add(dynamicEntity);
                    ++flag;
                }

            }
        }

        if (tempData.size() > 0) {//如果动态遍历完没有加入所有数据，加入it
            mData.addAll(tempData);
        }
        mHomeAdapter.setList(mData);

    }

    private void showNormalData(HomeData01Zip result) {
        List<HomeMultiItemEntity> mData = new ArrayList<>();


       /* if (result.getNoticeResults() != null && result.getNoticeResults().size() > 0 && !isRemoveNotice) {
            HomeMultiItemEntity noticeEntity = new HomeMultiItemEntity(HomeMultiItemEntity.HOME_NOTICE);
            noticeEntity.setNotice(result.getNoticeResults().get(0));
            mData.add(noticeEntity);
        }*/

      /*  if (result.getCommunityInfoResult() != null) {
            HomeMultiItemEntity bannerEntity = new HomeMultiItemEntity(HomeMultiItemEntity.HOME_BANNER);
            bannerEntity.setCommunityInfo(result.getCommunityInfoResult());
            mData.add(bannerEntity);
        }*/

        if (result.getCommunityNewsResult() != null) {
            HomeMultiItemEntity newsEntity = new HomeMultiItemEntity(HomeMultiItemEntity.HOME_COMMUNITY_NEWS);
            newsEntity.setCommunityNews(result.getCommunityNewsResult());
            mData.add(newsEntity);
        }

        if (result.getActiveResults() != null && result.getActiveResults().size() > 0) {
            HomeMultiItemEntity activeEntity = new HomeMultiItemEntity(HomeMultiItemEntity.HOME_ACTIVE);
            activeEntity.setActives(result.getActiveResults());
            mData.add(activeEntity);
        }
        if (result.getFriendRecoResults() != null && result.getFriendRecoResults().size() > 0) {
            HomeMultiItemEntity friendRecoEntity = new HomeMultiItemEntity(pIndex == 0 ? HomeMultiItemEntity.HOME_FRIEND_RECOMMEND_BETA : HomeMultiItemEntity.HOME_FRIEND_RECOMMEND);
            friendRecoEntity.setFriendList(result.getFriendRecoResults());
            mData.add(friendRecoEntity);
        }

        /*HomeMultiItemEntity dynamicEntity = new HomeMultiItemEntity(HomeMultiItemEntity.HOME_DYNAMIC);
        dynamicEntity.setDynamicList(result.getDynamicResults());
        mData.add(dynamicEntity);*/
        mData.addAll(HomeMultiItemEntity.getDynamicResults(result.getDynamicResults()));

        //mData = new ArrayList<>();
        mHomeAdapter.setList(mData);

    }

}
